// userPackage/pages/order/order.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    active: '',
    list: [{
        id: 5,
        text: '全部',
        page: 1,
        isFinish: false,
        orderList: []
      },
      {
        id: 0,
        text: '待付款',
        page: 1,
        isFinish: false,
        orderList: []
      },
      {
        id: 1,
        text: '待发货',
        page: 1,
        isFinish: false,
        orderList: []
      },
      {
        id: 2,
        text: '待收货',
        page: 1,
        isFinish: false,
        orderList: []
      },
      {
        id: 3,
        text: '待评价',
        page: 1,
        isFinish: false,
        orderList: []
      },
      {
        id: 4,
        text: '已取消',
        page: 1,
        isFinish: false,
        orderList: []
      },
    ],
    selectIndex: -1,
    size: 5,
    showHandle: false
  },

  toPage(e) {
    console.log(e);
    var obj = e.currentTarget.dataset.obj,
      flag = e.currentTarget.dataset.flag;

    if (flag == 'orderDetail' || flag == 'pay') {
      this.setData({
        showHandle: false
      })
      wx.navigateTo({
        url: '/userPackage/pages/orderDetail/orderDetail?order=' + JSON.stringify(obj),
      })
    } else if (flag == 'submit') {
      var arr = [],
        order = obj;
      order.orderInfoList.forEach(item => {
        arr.push({
          productImage: item.productImage,
          productName: item.productName,
          productKind: order.orderFlag == 1 ? 1 : 0,
          selectFormat: {
            factoryId: item.factoryId,
            formatId: item.formatId,
            formatName: item.formatName,
            productId: item.productId,
            selectNum: item.productNum,
            totalMoney: item.productTotal,
            productPrice: item.productPrice,
            productScore: item.productScore,
          }
        })
      })
      wx.navigateTo({
        url: '/orderPackage/pages/submitOrder/submitOrder?order=' + JSON.stringify(arr),
      })
    }
    // else if (flag == 'pay') {
    //   // 立即支付
    //   this.payHandle(obj)
    // }
    else if (flag == 'cancel') {
      // 取消订单
      console.log(obj.orderNumber);
      this.cancelOrConfirmOrderHandle(obj.orderId, 4)
    } else if (flag == 'wuLiu') {
      // 查看物流
      console.log(obj.orderNumber);
      wx.navigateTo({
        url: '/userPackage/pages/orderWuLiu/orderWuLiu?orderNum=' + obj.orderNumber,
      })

    } else if (flag == 'shouhuo') {
      // 确认收货
      this.cancelOrConfirmOrderHandle(obj.orderId, 3)
    } else if (flag == 'pingjia') {
      // 去评价
      wx.navigateTo({
        url: '/userPackage/pages/orderDetail/orderDetail?order=' + JSON.stringify(obj),
      })
    } else if (flag == 'del') {
      // 删除订单
      this.cancelOrConfirmOrderHandle(obj.orderId, 4)
    } else if (flag == 'show') {
      this.setData({
        showHandle: false
      })
    } else if (flag == 'returnGoods') {
      wx.navigateTo({
        url: '/orderPackage/pages/returnGoods/returnGoods?order=' + JSON.stringify(obj) + '&flag=1',
      })
    }
  },
  // 取消订单 确认收货
  cancelOrConfirmOrderHandle(orderId, status) {
    var url = app.globalData.url + "ScOrder/cancelOrder",
      that = this,
      list = this.data.list;
    wx.showModal({
      title: '提示',
      content: status == 4 ? '是否操作该订单' : '是否确认收货',
      complete: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '',
          })
          app.wxRequest(url, {
              orderId,
              status
            }, res => {
              console.log(res);
              if (res.flag) {
                wx.hideLoading()
                wx.showModal({
                  title: '提示',
                  content: '操作成功',
                  showCancel: false,
                  complete: (res) => {
                    if (res.confirm) {
                      var orderIndex = -1,
                        obj = '';
                      if (status == 4) {} else if (status == 3) {
                        list[3].orderList.forEach((ele, index) => {
                          if (ele.orderId == orderId) {
                            orderIndex = index
                            obj = ele
                          }
                        })
                        list[3].orderList.splice(orderIndex, 1)
                        list[4].orderList.unshift(obj)
                        this.setData({
                          list
                        })
                      }
                    }
                  }
                })
              }
            },
            err => {
              console.log(err);
            })
        }
      }
    })
  },
  // 支付
  payHandle(order) {
    var url = app.globalData.url + "pay/wxPay",
      that = this;
    wx.showLoading({
      title: '',
    })
    console.log(order);
    return;



    app.wxRequest(url, {
        openId: app.globalData.openId,
        userId: app.globalData.userId,
        totalMoney: order.realMoney,
        orderNum: order.orderNumber,
      }, res => {
        console.log(res);
        if (res.flag) {
          var datas = res.data.finalPackage;
          console.log(datas);
          wx.requestPayment({
            "timeStamp": datas.timeStamp,
            "nonceStr": datas.nonceStr,
            "package": datas.package,
            "signType": "RSA",
            "paySign": datas.paySign,
            "success": function (res) {
              console.log(res);
              if (res.errMsg == "requestPayment:ok") {
                //支付成功
                wx.showModal({
                  title: '提示',
                  content: '立即查看',
                  showCancel: false,
                  complete: (res) => {
                    if (res.confirm) {
                      //  前往订单页
                      that.getOrder()
                    }
                  }
                })
              }
            },
            "fail": function (res) {
              console.log(res);
              wx.showToast({
                title: '支付失败,请重试',
                icon: 'none'
              })
            },
            "complete": function (res) {
              console.log(res);
            }
          })

        }
      },
      err => {
        console.log(err);
      })
  },

  onChange(e) {
    console.log(e);
    this.setData({
      active: e.detail.name,
      selectIndex: this.getSelectIndex(e.detail.name)
    })
    console.log(this.data.active);
    console.log(this.data.list);
    console.log(this.data.list[this.data.selectIndex].orderList);
    if (this.data.list[this.data.selectIndex].orderList.length == 0) {
      this.getOrder()
    }
  },

  getSelectIndex(id) {
    console.log(id);
    var list = this.data.list,
      selectIndex = -1;
    list.forEach((item, index) => {
      if (item.id == id) {
        selectIndex = index
      }
    })
    console.log(selectIndex);
    return selectIndex
  },


  getOrder() {
    wx.showLoading({
      title: '',
    })
    var url = app.globalData.url + "ScOrder/listOrders",
      list = this.data.list,
      active = this.data.active,
      selectIndex = this.data.selectIndex,
      that = this;
    console.log(list);
    console.log(active);
    console.log(selectIndex);

    app.wxRequest(url, {
        status: active,
        page: list[selectIndex].page,
        size: that.data.size,
        userId: app.globalData.userId
      }, res => {
        console.log(res);
        if (res.flag) {
          var datas = res.data;
          console.log(selectIndex);
          if (selectIndex == 4) {
            datas.list.forEach(ele => {
              ele.isRateFinish = ele.orderInfoList.every(item => {
                return item.rateStatus == 1
              })
            })
          }
          console.log(datas.list);
          console.log(datas.list.length);
          list[selectIndex].isFinish = datas.list.length < that.data.size
          list[selectIndex].orderList.push(...datas.list)
          list[selectIndex].page++

          console.log(datas);
          wx.hideLoading()
          wx.stopPullDownRefresh()

          that.setData({
            list
          })
        }
      },
      err => {
        console.log(err);
      })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var id = Number(options.index || 4)
    this.setData({
      active: id,
      selectIndex: this.getSelectIndex(id)
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getOrder()
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    var list = this.data.list,
      selectIndex = this.data.selectIndex;
    list[selectIndex].page = 1
    list[selectIndex].isFinish = false
    list[selectIndex].orderList = []

    this.setData({
      list
    })
    this.getOrder()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    var list = this.data.list,
      selectIndex = this.data.selectIndex;
    if (list[selectIndex].isFinish) {
      wx.showToast({
        title: '暂无更多订单',
        icon: 'none'
      })
      return
    } else {
      this.getOrder()
    }

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})